/**
 - 设置 button中文字和图片的位置, 通过设置button的titleEdgeInsets 和 imageEdgeInsets属性 (设置其距离相对于button的距离)
 - 可以使用 UIButton+ImageTitleStyle 设置
 - 但是注意 要在能取到 button及其子控件的frame的设置
 - view 的 layoutIfNeeded (经过测试, iOS9并未执行该方法, 需要子啊 layoutSubviews方法中做相应设置)
 - controller 的 viewDidLayoutSubviews
 
 */


#import "TestButtonViewController.h"
#import "UIButton+ImageTitleStyle.h"


@interface TestButtonViewController ()
@property (nonatomic, strong) UIButton *button1;
@end

@implementation TestButtonViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    self.button1.frame = CGRectMake(100, 100, SCREEN_WIDTH / 3.f, 100);
    [self.view addSubview:self.button1];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    [self.button1 setButtonImageTitleStyle:ButtonImageTitleStyleTop padding:5];
}
- (UIButton *)button1 {
    if (!_button1) {
        _button1 = [[UIButton alloc] init];
        [_button1 setTitle:@"直接收益" forState:UIControlStateNormal];
        UIImage *image = [self wzm_imageWithColor:[UIColor redColor] forSize:CGSizeMake(30, 30) radius:0 borderWidth:0 borderColor:[UIColor redColor]];
        [_button1 setImage:image forState:UIControlStateNormal];
        [_button1 setTitleColor:[UIColor darkTextColor] forState:UIControlStateNormal];

        _button1.tag = 1;
        _button1.backgroundColor = [UIColor purpleColor];
    }
    return _button1;
}
- (UIImage *)wzm_imageWithColor:(UIColor *)color
                        forSize:(CGSize)size
                         radius:(CGFloat)radius
                    borderWidth:(CGFloat)borderWidth
                    borderColor:(UIColor *)borderColor
{
    CGRect rect = {CGPointZero, size};
    UIGraphicsBeginImageContextWithOptions(size, NO, 1.0);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    // 处理边框
    if (borderWidth > 0.0 && borderColor) {
        rect.size.width -= borderWidth;
        rect.size.height -= borderWidth;
        rect.origin.x += borderWidth * 0.5;
        rect.origin.y += borderWidth * 0.5;
        
        if (radius > 0.0) {
            CGFloat maxRagius = rect.size.width * 0.5;
            radius = radius > maxRagius ? maxRagius : radius;
        }
    }
    
    // 矩形
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRoundedRect(path, NULL, rect, radius, radius);
    CGContextAddPath(ctx, path);
    CGPathRelease(path);
    
    // 绘制
    [color setFill];
    if (borderWidth > 0.0 && borderColor) {
        [borderColor setStroke];
        CGContextSetLineWidth(ctx, borderWidth);
        CGContextDrawPath(ctx, kCGPathFillStroke);
    } else  {
        CGContextDrawPath(ctx, kCGPathFill);
    }
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}
@end
